package com.mall.order.mq.delayordere;

import lombok.extern.slf4j.Slf4j;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author: lds
 * @clsss: DelayOrderProducer
 * @description:
 */
@Component
@Slf4j
public class DelayOrderProducer {


    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        producer = new DefaultMQProducer("delay_order_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean  sendDelayOrderMessage(String orderId){

        //准备消息
        Message message = new Message();
        message.setTopic("delay_order");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));
        //设置延迟消息的延迟时间级别
        message.setDelayTimeLevel(10);
        SendResult sendResult =null;
        Exception ex=null;

        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            //输出异常日志信息
            ex=e;
        } catch (RemotingException e) {
            ex=e;
        } catch (MQBrokerException e) {
            ex=e;
        } catch (InterruptedException e) {
            ex=e;
        }
        if (sendResult != null&& SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            log.info("消息发送成功"+sendResult.getMsgId());
            return true;
        }else {
            log.info("消息发送失败"+ex);
            return false;
        }

    }
}
